import {
    getiInvoiceList,
    getiInvoiceApply,
    getiInvoiceDownload,
    addBillInfo,
    getBillInfo
} from '../../api/pay'
import user from '../../../utils/user'
import {
    dateFormat,
    toast,
    alert
} from '../../../utils/util'
const app = getApp()
Page({
    data: {
        month: '全部',
        pageNum: 1,
        pageSize: 20,
        totalCount: '',
        list: [],
        hasNextPage: true,
        monthList: ['全部', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
        date: '',
        billAddress: '',
        billPhone: '',
        billBankAccount: '',
        billBank: '',
        isBillInfo: false,
        billInfo: false,
        isAdmin: false,
        image: '',
        localImage: ''
    },
    onLoad() {
        user.waitLogin().then(() => {
            this.data.date = dateFormat('YYYY-', new Date())
            this.getiInvoiceList()
            this.getBillInfo()
            this.setData({
                isAdmin: user.isAdmin
            })
        })
    },
    onReady() {

    },
    onShow() {

    },
    getiInvoiceList() {
        console.log(this.data.date + this.data.month, 'this.data.date + this.data.month')
        getiInvoiceList({
            pageSize: this.data.pageSize,
            pageNum: this.data.pageNum,
            month: this.data.month == '全部' ? '' : this.data.date + this.data.month
        }).then(res => {
            console.log(res, 'res')
            if (!res.hasNextPage) {
                this.data.hasNextPage = false
            } else {
                this.data.hasNextPage = true
            }
            const arr = []
            arr.push(...this.data.list)
            arr.push(...res.list)
            this.setData({
                list: arr
            })
        })
    },
    selectDate(event) {
        console.log(event, 'event')
        const {
            value
        } = event.detail
        this.data.monthList.forEach((item, index) => {
            if (value == index) {
                this.setData({
                    month: item,
                    pageNum: 1,
                    list: []
                })
                this.getiInvoiceList()
            }
        })
    },
    threshold() {
        if (!this.data.hasNextPage) {
            return
        }
        this.data.pageNum += 1
        this.getiInvoiceList()
    },
    onGoDetail(event) {
        const {
            id
        } = event.currentTarget.dataset
        console.log('点击下载')
        wx.navigateTo({
            url: '/packagePay/pages/invoice-detail/invoice-detail?id=' + id,
        })
    },
    onGobillInfo() {
        this.setData({
            isBillInfo: false
        })
        wx.navigateTo({
            url: '/packagePay/pages/invoice-info/invoice-info',
        })
    },
    // 关闭发票信息弹窗
    hideBillPopup() {
        this.setData({
            isBillInfo: false
        })
    },
    async getiInvoiceApply(event) {
        await this.getBillInfo()
        const {
            id,
            type,
            invoicename
        } = event.currentTarget.dataset
        console.log(id, type, 'event')
        if (type === 0) {
            if (!this.data.billInfo && this.data.isAdmin) {
                this.setData({
                    isBillInfo: true
                })
                return
            }
            if (!this.data.billInfo && !this.data.isAdmin) {
                alert('因系统升级，需完善开票信息，请联系管理员到此页面完善信息后申请/下载发票')
                return
            }
            getiInvoiceApply({
                id: id
            }).then(res => {
                console.log(res, 'res')
                app.toast('申请成功')
                setTimeout(() => {
                    this.setData({
                        list: []
                    })
                    this.getiInvoiceList()
                }, 300)

            })
        } else if (type === 1) {
            app.toast('请耐心等待')
        } else if (type === 2) {
            if (!this.data.billInfo && this.data.isAdmin) {
                this.setData({
                    isBillInfo: true
                })
                return
            }
            if (!this.data.billInfo && !this.data.isAdmin) {
                alert('因系统升级，需完善开票信息，请联系管理员到此页面完善信息后申请/下载发票')
                return
            }
            getiInvoiceDownload({
                id: id
            }).then(res => {
                console.log(res.url)
                this.setData({
                    image: res.url
                })
                let sr = res.url.lastIndexOf('.')
                let fileType = res.url.substr((sr + 1))

                wx.showLoading({
                    mask: true,
                    title: '加载中'
                })
                wx.downloadFile({
                    url: res.url,
                    filePath: wx.env.USER_DATA_PATH + '/' + invoicename + '.' + fileType,
                    success: async (res) => {
                        console.log(res, '下载成功')
                        wx.hideLoading()
                        if (fileType == 'jpg' || fileType == 'png') {
                            const result = await wx.getSetting()
                            console.log(result, '文件权限')
                            if (!result.authSetting['scope.writePhotosAlbum']) {
                                wx.authorize({
                                    scope: 'scope.writePhotosAlbum',
                                    success: () => {
                                        wx.saveImageToPhotosAlbum({
                                            filePath: res.filePath,
                                            complete: (res) => {
                                                console.log(res, '文件存储')
                                            }
                                        })
                                        wx.previewImage({
                                            current: this.data.image,
                                            urls: [this.data.image],
                                            showmenu: true
                                        })
                                    },
                                    fail: (rej) => {
                                        console.log(rej, '位置获取失败')
                                    }
                                })
                            }
                            if (result.authSetting['scope.writePhotosAlbum']) {
                                wx.saveImageToPhotosAlbum({
                                    filePath: res.filePath,
                                    complete: (res) => {
                                        console.log(res, '文件存储')
                                    }
                                })
                                wx.previewImage({
                                    current: this.data.image,
                                    urls: [this.data.image],
                                    showmenu: true
                                })
                            }

                            return
                        }
                        wx.openDocument({
                            filePath: res.filePath,
                            showMenu: true,
                            fileType: fileType,
                            success: () => {
                                this.setData({
                                    pageNum: 1,
                                    list: []
                                })
                                this.getiInvoiceList()
                            },
                            fail: () => {
                                console.log(res, 'resres')
                                wx.hideLoading()
                                // app.toast('文件打开失败')
                            },
                        })
                    },
                    fail: (rej) => {
                        wx.hideLoading()
                        app.toast('下载失败')
                        console.log(rej, '失败')
                    }
                })
            })
        }
    },
    // 获取发票信息
    async getBillInfo() {
        const result = await getBillInfo()
        this.setData({
            billInfo: result
        })
        console.log(this.data.billInfo, 'getBillInfo信息返回')
    },
    // 提交发票信息
    async onSubmitBillInfo() {
        if (!this.data.billAddress) {
            toast('请填写公司地址')
            return
        }
        if (!this.data.billPhone) {
            toast('请填写公司联系方式')
            return
        }
        if (this.data.billPhone !== '' && !/^1\d{10}$/.test(this.data.billPhone)) {
            toast('请填写正确的手机号码！')
            return
        }
        if (!this.data.billBankAccount) {
            toast('请填写对公账号')
            return
        }
        if (!this.data.billBank) {
            toast('请填写对公账户开户行')
            return
        }
        await addBillInfo({
            companyAddress: this.data.billAddress,
            phone: this.data.billPhone,
            bankNo: this.data.billBankAccount,
            openBank: this.data.billBank
        })
        toast('提交成功')
        await this.getBillInfo()
        this.setData({
            isBillInfo: false
        })
        console.log(this.data.billAddress, 'billAddress')
    },
})